package com.ltmall.api.controller;

import com.ltmall.api.manager.AccountManager;
import com.ltmall.api.manager.DirectorPrivilegeOrderManager;
import com.ltmall.api.util.RemoteUtil;
import com.ltmall.api.weixin.pay.Constants;
import com.ltmall.api.weixin.pay.utils.WeixinUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

@Controller
public class DirectorPrivilegeOrderController {

    private AccountManager accountManager;
    private DirectorPrivilegeOrderManager directorPrivilegeOrderManager;

    public void create(HttpServletRequest request, HttpServletResponse response) {
        boolean valiTag = accountManager.validate(Integer.parseInt(request.getParameter("userID")),
                request.getParameter("userToken"));
        if (!valiTag) {
            RemoteUtil.response(response, null, -100, "身份异常");
            return;
        }

        int userID = Integer.parseInt(request.getParameter("userID"));
        int packageID = Integer.parseInt(request.getParameter("packageID"));
        try {
            Map<String, String> result = directorPrivilegeOrderManager.create(userID, packageID, getIpAddr(request), request.getParameter("openID"));
            RemoteUtil.response(response, result, 1, "返回成功");

        } catch (Exception e) {
            RemoteUtil.response(response, null, -1, e.getMessage());
        }
    }

    public void wxNotify(HttpServletRequest request, HttpServletResponse response) {
        InputStream inputStream = null;
        Map<String, String> map = null;
        try {
            // 解析结果存储在TreeMap
            map = new TreeMap<String, String>();
            inputStream = request.getInputStream();
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            @SuppressWarnings("unchecked")
            List<Element> elementList = root.elements();
            // 遍历所有子节点
            for (Element e : elementList) {
                if (e.getName() != null && e.getText() != null) {
                    map.put(e.getName(), "" + e.getText());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (inputStream != null) {
                    inputStream.close();
                    inputStream = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        boolean paySuccess = true;

        /*
         * map处理
         */
        if (!map.get("return_code").equals("SUCCESS")) {
            paySuccess = false;
        }

        // 签名验证
        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = map.get(key);
            if (!key.equals("sign") && value != null) {
                signParams.add(new BasicNameValuePair(key, value));
            }
        }

        String computationalSign = WeixinUtils.genSign(signParams);
        String originalSign = map.get("sign");
        if (!computationalSign.equals(originalSign)) {
            paySuccess = false;
        }

        // 结果验证
        if (!map.get("result_code").equals("SUCCESS")) {
            paySuccess = false;
        }

        // appid验证
        String appId = (map.get("trade_type").equals("APP") ? Constants.APP_ID : Constants.OA_APP_ID);
        if (!map.get("appid").equals(appId)) {
            paySuccess = false;
        }

        // 商户id验证
        String mchId = (map.get("trade_type").equals("APP") ? Constants.MCH_ID : Constants.OA_MCH_ID);
        if (!map.get("mch_id").equals(mchId)) {
            paySuccess = false;
        }

        if (paySuccess) {
            String tradeNo = map.get("out_trade_no");
            try {
                directorPrivilegeOrderManager.setSuccess(tradeNo);
                response.resetBuffer();
                response.setContentType("text/xml; charset=UTF-8");
                String returnXml = null;
                if (paySuccess) {
                    returnXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                } else {
                    returnXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                }

                try {
                    PrintWriter writer = response.getWriter();
                    writer.print(returnXml);
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {

            }
        }
    }
	
	/*public void testDirectorPrivilege(HttpServletRequest request, HttpServletResponse response){
	   String tradeNo=request.getParameter("tradeNo");
	    directorPrivilegeOrderManager.setSuccess(tradeNo);
	}*/

    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = "192.168.1.1"; // 实在出问题时没办法
        }

        int commaOffset = ip.indexOf(',');
        if (commaOffset < 0) {
            return ip;
        } else {
            return ip.substring(0, commaOffset);
        }
    }

    public AccountManager getAccountManager() {
        return accountManager;
    }

    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    public DirectorPrivilegeOrderManager getDirectorPrivilegeOrderManager() {
        return directorPrivilegeOrderManager;
    }

    public void setDirectorPrivilegeOrderManager(DirectorPrivilegeOrderManager directorPrivilegeOrderManager) {
        this.directorPrivilegeOrderManager = directorPrivilegeOrderManager;
    }
}